<template>
  <div class="add-friend-auto">
    <div class="add-friend-auto-content scroll">
      <!-- 上传text文件 -->
      <!-- <div class="uplode-number">
        <template v-if="phones.length === 0">
          <img src="../../../assets/images/tools/uploadPhones.png" alt="导入号码" />
          <label style="cursor: pointer; color: #576c95; font-size: 14px" for="chosePhoneText" class="tip">
            导入号码
          </label>
          <input
            v-show="false"
            id="chosePhoneText"
            class="tip"
            type="file"
            accept="text/plain"
            @change="openFile($event)"
          />
          <p style="color: #999999; font-size: 12px">
            <a class="a_download" target="_blank" href="http://www.jjldkj.com/files/weixin/phones.txt" download>
              下载模板
            </a>
          </p>
        </template>
        <template v-else>
          <p>共导入</p>
          <p style="font-size: 30px; color: #576c95" v-text="phones.length"></p>
          <p>微信/号码</p>
          <div>
            自动分配
            <el-switch
              v-model="autoDistribution"
              size="small"
              active-color="#576C95"
              inactive-color="#EEEEEE"
            ></el-switch>
          </div>
          <label style="cursor: pointer; color: #576c95; font-size: 12px" for="chosePhoneText" class="tip">
            重新导入
          </label>
          <input
            v-show="false"
            id="chosePhoneText"
            class="tip"
            type="file"
            accept="text/plain"
            @change="openFile($event)"
          />
        </template>
      </div> -->
      <!-- 微信列表 -->
      <div
        v-for="(wechat, index) in wechatsOnline"
        :key="index"
        class="wechat-info"
        :class="{ 'wechat-item': index % 5 === 3 }"
      >
        <div class="avatar-info">
          <el-avatar :size="44" :src="wechat.Avatar">
            <i class="fa fa-picture-o" aria-hidden="true" title="头像miss"></i>
          </el-avatar>
          <div class="other-info">
            <p
              class="ellipsis"
              style="color: #333333; font-size: 14px"
              :title="wechat.WeChatNick"
              v-text="wechat.WeChatNick"
            ></p>
            <p class="ellipsis" :title="wechat.WeChatNo" v-text="wechat.WeChatNo"></p>
            <p class="ellipsis">
              <span v-text="wechat.Province"></span>
              &nbsp;
              <span v-text="wechat.City"></span>
            </p>
          </div>
        </div>
        <div class="number-input">
          <span>每天添加数量</span>
          <el-input-number
            v-model="numberMap[wechat.WeChatId]"
            style="width: 100px; margin: 0 7px"
            size="small"
            :min="0"
            :max="limitNumber"
            :step="1"
            step-strictly
            :disabled="autoDistribution"
          ></el-input-number>
          个
        </div>
      </div>
    </div>

    <!-- 验证消息 -->
    <div class="verify-message">
      <span style="width: 90px" class="tip">验证消息</span>
      <el-input v-model="verifyMessage" size="small" placeholder="请输入验证消息"></el-input>
    </div>

    <!-- 创建任务 -->
    <div class="add-friend-auto-oprations">
      <div class="break-time">
        <span class="tip">添加限制</span>
        <el-input-number
          v-model="limitNumber"
          size="small"
          controls-position="right"
          :min="1"
          :max="100"
          style="margin: 0 5px; width: 90px"
        ></el-input-number>
      </div>
      <div class="break-time">
        <span class="tip">时间间隔(分)</span>
        <el-input-number
          v-model="breakTime"
          size="small"
          controls-position="right"
          :min="1"
          :max="59"
          style="margin: 0 5px; width: 90px"
        ></el-input-number>
      </div>
      <div class="start-time">
        <span class="tip">起始时间</span>
        <el-date-picker
          v-model="startTime"
          type="datetime"
          placeholder="选择日期时间"
          clearable
          size="small"
        ></el-date-picker>
      </div>

      <el-button
        size="small"
        type="info"
        plain
        style="color: #999999; background: #fff; border: solid 1px #dadada"
        @click="showTaskDialog"
      >
        任务日志
      </el-button>
      <el-button
        size="small"
        type="primary"
        style="color: #fff; background: #ff9f00; border: solid 1px #ff9f00"
        :disabled="sending"
        :loading="sending"
        @click="sureSend"
      >
        创建任务
      </el-button>
    </div>

    <!-- 任务日志 -->
    <el-dialog append-to-body title="SOP任务加好友日志" :visible.sync="taskLogVisiable">
      <el-table :data="logs" stripe height="500px">
        <el-table-column type="index" label="序号" width="60px"></el-table-column>
        <el-table-column label="微信昵称">
          <template slot-scope="scope">
            <span
              v-if="scope.row.wechatid && wechatsNameMap[scope.row.wechatid]"
              v-text="wechatsNameMap[scope.row.wechatid]"
            ></span>
            <span v-else>{{ scope.row.wechatid }}</span>
          </template>
        </el-table-column>
        <el-table-column label="验证消息" prop="message"></el-table-column>
        <el-table-column label="可用号码数" prop="" width="100">{{ phoneAvailable }}</el-table-column>

        <el-table-column label="执行次数">
          <template slot-scope="scope">{{ scope.row.doingsize }}</template>
        </el-table-column>
        <el-table-column label="成功次数">
          <template slot-scope="scope">
            <span style="color: #67c23a" v-text="scope.row.successsize"></span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="失败次数">
          <template slot-scope="scope">
            <span
              v-if="scope.row.doingsize && scope.row.successsize"
              style="color: red"
              v-text="scope.row.doingsize - scope.row.successsize"
            ></span>
          </template>
        </el-table-column> -->
        <el-table-column label="总次数">
          <template slot-scope="scope">{{ scope.row.totalsize }}</template>
        </el-table-column>
        <el-table-column label="任务结果">
          <template slot-scope="scope">
            <span v-text="scope.row.state === 0 ? '已结束' : '进行中'"></span>
          </template>
        </el-table-column>
        <el-table-column prop="execute_time" label="下次执行时间" width="150px"></el-table-column>
        <!--  -->
        <el-table-column label="操作" width="160">
          <template slot-scope="{ row }">
            <el-button v-if="row.state === 1" type="text" size="small" @click="modifyState(row, -1)">暂停</el-button>
            <el-button v-if="row.state === -1" type="text" size="small" @click="modifyState(row, 1)">继续</el-button>
            <el-button v-if="row.state === 1 || row.state === -1" type="text" size="small" @click="modifyState(row, 2)">
              取消
            </el-button>
            <el-button type="text" size="small" @click="deleteTask(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="display: flex; justify-content: center"
        :current-page="pageNo"
        :page-sizes="[15, 30, 45, 60]"
        :page-size="pageSize"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  autoFriendAddTask,
  getAutoFriendAddTaskList,
  friendAddTaskDelete,
  friendAddTaskStateUpdate
} from '@/api/httpApi'

export default {
  name: 'ToolsAddFriendAuto',
  data() {
    return {
      // phones: [],
      autoDistribution: false, // 自动分配
      numberMap: {}, // 每个微信的添加数量
      limitNumber: 15, // 添加上限

      startTime: new Date().getTime(), // 添加的起始时间
      breakTime: 1, // 添加的间隔时间
      verifyMessage: '', // 验证消息
      taskLogVisiable: false, // 显示日志
      sending: false, // 显示日志
      logs: [],
      phoneAvailable: 0, // 添加上限
      total: 0,
      pageSize: 15, // 每页几个数据
      pageNo: 1 // 当前页
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      wechats: 'conversation/wechats',
      wechatsNameMap: 'conversation/wechatsNameMap',
      wechatsOnline: 'conversation/wechatsOnline'
    })
    // // 测试数据
    // wechatsTest() {
    //   const wc = []
    //   for (let i = 0; i < 10; i++) {
    //     for (const iterator of this.wechatsOnline) {
    //       wc.push(iterator)
    //     }
    //   }
    //   return wc
    // },
  },
  watch: {
    // 监听自动分配
    // autoDistribution(val) {
    //   if (val) {
    //     this.autoDispatch()
    //   }
    // }
  },
  created() {
    // 设置每个微信加的初始值
    this.wechatsOnline.forEach((e) => {
      this.$set(this.numberMap, e.WeChatId, 15)
    })
  },
  methods: {
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
      this.queryLogs()
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.pageNo = val
      this.queryLogs()
    },
    // 查看日志
    queryLogs() {
      getAutoFriendAddTaskList(
        this.currentUser.SupplierId,
        this.currentUser.UnionId,
        '',
        this.pageNo,
        this.pageSize
      ).then((res) => {
        const { count, list } = res.data
        if (res.code === 0) {
          this.logs = list.list || []
          this.total = list.total || 0
          this.phoneAvailable = count
        }
      })
    },
    // // 解析txt
    // openFile(event) {
    //   const file = event.target.files[0]
    //   const reader = new FileReader()
    //   if (file) {
    //     reader.readAsText(file)
    //     reader.onload = (evt) => {
    //       // 读取完文件之后会回来这里
    //       const fileString = evt.target.result // 读取文件内容
    //       this.phones = fileString.split(/\r\n|\n/)
    //       // this.phones = fileString.split('\r\n')
    //       // 自动分配手机号
    //       if (this.phones.length > 0 && this.autoDistribution) {
    //         this.autoDispatch()
    //       }
    //     }
    //   } else {
    //     this.phones = []
    //   }
    // },
    // // 自动分配号码
    // autoDispatch() {
    //   const eachP = this.phones.length / this.wechatsOnline.length
    //   this.wechatsOnline.forEach((e, index) => {
    //     if (index === this.wechatsOnline.length - 1) {
    //       this.$set(this.numberMap, e.WeChatId, Math.floor(eachP))
    //     } else {
    //       this.$set(this.numberMap, e.WeChatId, Math.round(eachP))
    //     }
    //   })
    // },
    // // 添加数量的最大值
    // getMaxNumber(wxid) {
    //   let tn = 0
    //   for (const key in this.numberMap) {
    //     if (this.numberMap.hasOwnProperty(key) && key !== wxid) {
    //       const element = this.numberMap[key]
    //       tn += element
    //     }
    //   }
    //   const maxP = this.phones.length - tn
    //   return maxP > 0 ? maxP : 0
    // },
    // 时间戳转换成 2020-09-21 16:44
    transformTime(times) {
      const date = new Date(times)
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      // let s = date.getSeconds()
      const time = Y + M + D + h + m
      return time
    },
    // 提交表单
    sureSend() {
      const config = []
      for (const key in this.numberMap) {
        if (this.numberMap.hasOwnProperty(key)) {
          config.push({
            wechatid: key,
            add_count: this.numberMap[key]
          })
        }
      }
      autoFriendAddTask(
        this.currentUser.UnionId,
        this.transformTime(this.startTime),
        this.breakTime,
        config,
        '',
        this.verifyMessage
      )
        .then((res) => {
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '创建自动加好友任务成功！',
              duration: 1000
            })
          } else {
            this.$message({
              type: 'error',
              message: '创建自动加好友任务失败！',
              duration: 1000
            })
          }
          this.sending = false
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.sending = false
        })
      this.sending = true
    },
    // 获取并显示批量加好友任务列表
    showTaskDialog() {
      this.queryLogs()
      this.taskLogVisiable = !this.taskLogVisiable
    },
    // 删除任务
    deleteTask(row) {
      friendAddTaskDelete(row.id).then((res) => {
        if (res.code === 0) {
          this.$message.success('删除成功！', res)
          this.logs = this.logs.filter((x) => {
            return x.id !== row.id
          })
          this.total = this.total - 1
        }
      })
    },
    // 修改任务状态
    modifyState(row, state) {
      friendAddTaskStateUpdate(row.id, state).then((res) => {
        if (res.code === 0) {
          for (const gsl of this.logs) {
            if (gsl.id === row.id) {
              gsl.state = state
              break
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.add-friend-auto {
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .add-friend-auto-content {
    flex: 1 1 auto;
    padding: 16px;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    overflow: auto;

    .uplode-number,
    .wechat-info {
      width: 220px;
      height: 147px;
      border: solid #eeeeee 1px;
      border-radius: 5px;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: space-evenly;
      font-size: 14px;
      color: #999999;
      margin: 0 12px 16px 0;
    }
    .wechat-info {
      justify-content: space-between;
      .avatar-info {
        flex: 1 1 auto;
        display: flex;
        align-items: center;
        // border: solid red 1px;
        .other-info {
          display: flex;
          flex-direction: column;
          p {
            padding: 5px 10px;
            font-size: 12px;
            width: 100px;
          }
        }
      }
      .number-input {
        width: 220px;
        height: 49px;
        font-size: 12px;
        color: #333333;
        border-radius: 0 0 5px 5px;
        background-color: #f8f8f8;

        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .wechat-item {
      margin-right: 0;
    }
  }

  .verify-message {
    margin: 0 20px;
    display: flex;
    align-items: center;
    min-height: 50px;
  }

  .add-friend-auto-oprations {
    height: 50px;
    min-height: 50px;
    width: 100%;
    background-color: #f9f9f9;
    font-size: 14px;
    color: #333333;
    display: flex;
    // justify-content: space-around;
    align-items: center;
    padding: 0 20px;

    .break-time,
    .start-time {
      padding: 0 25px 0 0;
      display: flex;
      align-items: center;
      .tip {
        margin-right: 10px;
        font-size: 16px;
      }
    }
  }
}
</style>
